package util

import (
	"gin-blog/pkg/setting"
	"github.com/dgrijalva/jwt-go"
	"time"
)

var jwtSecret = []byte(setting.AppSetting.JwtSecret)

type Claims struct {
	Username string `json:"username"`
	Password string `json:"password"`
	jwt.StandardClaims
}

//生成Token
func GenerateToken(username ,password string) (string ,error){
	nowTime := time.Now()

	expireTime := nowTime.Add(3 * time.Hour)

	claims:= Claims{
		username,
		password,
		jwt.StandardClaims{
			ExpiresAt:expireTime.Unix(),
			Issuer:"gin-blog",
		},
	}

	tokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	//生成签名字符串
	token, err := tokenClaims.SignedString(jwtSecret)
	
	return token,err
}

//解析Token
func ParseToken(token string) (*Claims, error){
	//解析鉴权的声明
	tokenClaims, err := jwt.ParseWithClaims(token, &Claims{}, func(token *jwt.Token) (i interface{}, e error) {
		return jwtSecret, nil
	})

	if tokenClaims !=nil{
		if claims, ok :=tokenClaims.Claims.(*Claims);ok && tokenClaims.Valid{
			return claims,nil
		}
	}

	return nil,err
}